package com.sea.finance.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.data.entity.SalesForecast;
import com.sea.finance.entity.*;
import com.sea.finance.service.ExchangeRateRecordService;
import com.sea.finance.service.ExchangeRateService;
import com.sea.finance.service.VtFileService;
import com.sea.finance.service.VtService;
import com.sea.physical.entity.CreateDespatchFreight;
import com.sea.physical.entity.CreateSku;
import com.sea.supply.entity.Buy;
import lombok.Synchronized;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


/**
 * 运费
 * @author 陈鸿飞
 */
@Controller
@RequestMapping(value = "/sea/finance/vt")
public class VtController {
    @Autowired
    private VtService vtService;
    @Autowired
    private VtFileService vtFileService;
    @Autowired
    private DictDetailService dictDetailService;
    @Autowired
    private ExchangeRateService exchangeRateService;
    @Autowired
    private ExchangeRateRecordService exchangeRateRecordService;

    private List<String> header;

    private List<Map<String, Object>> body;
    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("shop", dictDetailService.findByTypeCode("base_shop", null));
        model.addAttribute("brand", dictDetailService.findByTypeCode("base_brand", null));
        model.addAttribute("country", dictDetailService.findByTypeCode("base_country", null));
        return "/sea/finance/vtReport/main";
    }

    @RequestMapping("/dealNonAmazonMain")
    public String dealNonAmazonMain(Model model) {
        return "/sea/finance/vtReport/dealNonAmazonMain";
    }

    @RequestMapping("/report/main")
    public String report(Model model) {
        model.addAttribute("shop", dictDetailService.findByTypeCode("base_shop", null));
        model.addAttribute("brand", dictDetailService.findByTypeCode("base_brand", null));
        model.addAttribute("country", dictDetailService.findByTypeCode("base_country", null));
        return "/sea/finance/vtReport/report";
    }

    @RequestMapping("/getStockHeader")
    @ResponseBody
    public List<String> getStockHeader(){


        List<String> list=new ArrayList<>();
        list.add("主体");
        list.add("店铺");
        list.add("国家");
        list.add("SKU");
        list.add("Listing");
        list.add("订单");
        list.add("1-项目销售收入");
        list.add("折扣");
        list.add("2-项目赔偿收入");
        list.add("5-平台退款");
        list.add("6-佣金费");
        list.add("10-FBA配送费");
        list.add("入库配置费");
        list.add("Z 仓储费 账单");
        list.add("Z 仓储费-卫星仓 账单");
        list.add("12-营销费");
        list.add("11-服务费");
        list.add("Amazon Product Tax");
        list.add("平台代扣代缴税款");
        list.add("Z Current Reserve Amount");
        list.add("Z Previous Reserve Amount Balance");
        list.add("disposal费");
        list.add("海运费");
        list.add("关税");

        header=list;
        return list;
    }

    @RequestMapping("/getStockBody")
    @ResponseBody
    public List<Map<String, Object>> getStockBody(@RequestParam("period")String period,
                                                  @RequestParam("shop_name")String shop_name,
                                                  @RequestParam("brand_name")String brand_name,
                                                  @RequestParam("country_name")String country_name,
                                                  @RequestParam("sku")String sku,
                                                  @RequestParam("listing_name")String listing_name,
                                                  @RequestParam("moneyType")String moneyType){
        List<Map<String, Object>> mapList = new ArrayList<>();
        VtFile vtFile=new VtFile();
        vtFile.setShopName(shop_name);
        vtFile.setBrandName(brand_name);
        vtFile.setCountryName(country_name);
        vtFile.setPeriod(period);
        List<VtFile> list = vtFileService.findByCnd(vtFile);

        if(null != list && list.size() !=0){
            for(VtFile vf : list){
                String orgMoneyType=null;
                Vt vt=new Vt();
                vt.setPeriod(vf.getPeriod());
                vt.setShop_name(vf.getShopName());
                vt.setBrand_name(vf.getBrandName());
                vt.setCountry_name(vf.getCountryName());
                vt.setSku(sku);
                vt.setListing_name(listing_name);
                //判断币种是否一致
                switch (vf.getCountryName()) {
                    case "US":
                        orgMoneyType="美金";
                        break;
                    case "UK":
                        orgMoneyType="英镑";
                        break;
                    case "EU":
                    case "DE":
                    case "FR":
                    case "IT":
                    case "ES":
                        orgMoneyType="欧元";
                        break;
                    case "CA":
                        orgMoneyType="加元";
                        break;
                    default:
                        break;
                }
                //判断是否需要进行汇率换算
                if(StringUtils.isNotBlank(moneyType)) {
                    //如果目标币种和原币种一致
                    if (orgMoneyType.equals(moneyType)) {
                        vt.setOrg_rate(1.00);
                        vt.setTag_rate(1.00);
                    } else {
                        //查询汇率
                        if (StringUtils.isNotBlank(orgMoneyType) && StringUtils.isNotBlank(moneyType)) {
                            ExchangeRate tagRate = exchangeRateService.findByRateName("CNY", moneyType);
                            if (null != tagRate) {
                                ExchangeRateRecord tagRecord = exchangeRateRecordService.findByPeriod(tagRate.getId(), period);
                                if (null != tagRecord) {
                                    //设置目标币种当月汇率
                                    vt.setTag_rate(tagRecord.getRatePercent());
                                }
                            }

                            ExchangeRate orgRate = exchangeRateService.findByRateName("CNY", orgMoneyType);
                            if (null != orgRate) {
                                ExchangeRateRecord orgRecord = exchangeRateRecordService.findByPeriod(orgRate.getId(), period);
                                if (null != orgRecord) {
                                    //设置原币种当月汇率
                                    vt.setOrg_rate(orgRecord.getRatePercent());
                                }
                            }
                        } else {
                            vt.setOrg_rate(1.00);
                            vt.setTag_rate(1.00);
                        }
                    }
                }else {
                    vt.setOrg_rate(1.00);
                    vt.setTag_rate(1.00);
                }

                //查询SKU+Listing组
                List<Map<String, Object>> dataList = vtService.findByReport(vt);
                for(int i=0;i<dataList.size();i++){
                    mapList.add(dataList.get(i));
                }
                //查询空白组
                List<Map<String, Object>> dataList2 = vtService.findNullByReport(vt);
                for(int i=0;i<dataList2.size();i++){
                    mapList.add(dataList2.get(i));
                }
                //查询公共费用组
                List<Map<String, Object>> dataList3 = vtService.findListingByReport(vt);
                for(int i=0;i<dataList3.size();i++){
                    mapList.add(dataList3.get(i));
                }
            }
        }
        //汇率换算
        body = mapList;
        return mapList;
    }

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/dealSkuMain")
    public String dealSkuMain(Model model) {
        return "/sea/finance/vtReport/dealSkuMain";
    }

    @ResponseBody
    @RequestMapping("/findByDealSku")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Vt vt) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Vt> list = vtService.findByDealSku(vt);
        PageInfo<Vt> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }
    @ResponseBody
    @RequestMapping("/findByNonAmazonSku")
    public AjaxTableReturn findByNonAmazonSku(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Vt vt) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Vt> list = vtService.findByNonAmazon(vt);
        PageInfo<Vt> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }


    @RequestMapping("/importDealSku")
    @ResponseBody
    public AjaxReturn importDetail(Model model, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xlsx")) || !(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                vtService.importDealSku(file.getInputStream(),fileName);
                vtService.updateListingName();
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    @RequestMapping("/importDealAmazonOrder")
    @ResponseBody
    public AjaxReturn importDealAmazonOrder(Model model, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                vtService.importDealAmazonOrder(file.getInputStream(),fileName);

                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    @RequestMapping("/importAmazonOrder")
    @ResponseBody
    public AjaxReturn importAmazonOrder(Model model, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                vtService.importAmazonOrder(file.getInputStream(),fileName);

                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }



    @RequestMapping("/importDetail")
    @ResponseBody
    @Synchronized
    public AjaxReturn importDetail(Model model, MultipartFile importSession,
                                   @RequestParam("period")String period,
                                   VtFile vtFile) {

        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == importSession || importSession.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = importSession.getOriginalFilename();
                String fileUrl = vtService.uploadVtFile(fileName, importSession.getInputStream());
                vtFile.setFileName(fileName);

                vtFile.setFlag(0);
                vtFile.setFileUrl(fileUrl);
                vtFileService.save(vtFile);
                result.setOk(true).setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/reload", method = RequestMethod.POST)
    public AjaxReturn reload() {
        AjaxReturn result = Ajax.fail().setMsg("获取失败！");
        try{
            vtService.reload();
            VtFile vtFile=new VtFile();
            vtFile.setFileName("已清空V2数据");
            vtFile.setFlag(3);
            vtFileService.save(vtFile);
            result.setOk(true).setMsg("获取成功！");
        }catch (RuntimeException e){
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, Vt vt) {
        List<Vt> list = vtService.findByDealSku(vt);
        String[] title = {"编号","order_id","transaction_type","sku","fee_name","listing_name","settlement_id","merchant-order-id","posted-date","fee_type"};
        String fileName = "费用归集表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "费用归集表";
        String[][] content = new String[list.size()][10];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Vt obj = list.get(i);
            content[i][0] = obj.getId()+"";
            content[i][1] = obj.getOrder_id();
            content[i][2] = obj.getTransaction_type();
            content[i][3] = obj.getSku();
            content[i][4] = obj.getFee_name();
            content[i][5] = obj.getListing_name();
            content[i][6] = obj.getSettlement_id();
            content[i][7] = obj.getMerchant_order_id();
            content[i][8] = obj.getPosted_date();
            content[i][9] = obj.getFee_type();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    @RequestMapping("/exportReport")
    @ResponseBody
    public void exportReport(HttpServletResponse response) {
        String[] title = new String [header.size()];
        for(int i=0;i<title.length;i++){
            title[i]=header.get(i);
        }
        String fileName = "报表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "报表";
        String[][] content = new String[body.size()][title.length];
        for (int i = 0; i < body.size(); i++) {
            content[i] = new String[title.length];
            Map<String, Object> map = body.get(i);
            Iterator entries = map.entrySet().iterator();
            Integer j=0;
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                Object key = (Object) entry.getKey();
                Object value = (Object) entry.getValue();
                for(int k=0;k<title.length;k++){
                    if((key+"").equals(title[k])){
                        content[i][k] = value+"";
                    }
                }
                j=j+1;
            }
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, getTitle(title), content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String[] getTitle(String[] list){
        String[] newList=new String[list.length];
        for(int i=0;i<list.length;i++){
            String str=list[i];
            switch (str){
                case "SKU":
                    newList[i]="SKU";
                    break;
                case "Listing":
                    newList[i]="Listing";
                    break;
                default :
                    newList[i]=(str);
            }
        }
        return newList;
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @RequestMapping(value = "/exportNonAmazonOrder")
    @ResponseBody
    public void exportNonAmazon(HttpServletRequest request, HttpServletResponse response, Vt vt) throws IOException {
        List<Vt> list = vtService.findByNonAmazon(vt);
        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("非亚马逊订单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 自定义表头顺序（按需要的顺序排列）
        List<List<String>> customHead = new ArrayList<>();
        customHead.add(Arrays.asList("Order_id"));


        // 3. 导出Excel
        EasyExcel.write(response.getOutputStream(), Buy.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .sheet("非亚马逊订单")
                .head(customHead)  // 设置自定义表头
                .doWrite(convertDataToNonAmazonOrder(list)); // 转换数据顺序
    }

    @ResponseBody
    @RequestMapping(value = "/exportDealSku", method = RequestMethod.GET)
    public void exportDealSku(HttpServletResponse response) throws IOException {
        List<Vt> list = vtService.findByDealSku(null);;
        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("待处理SKU", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 自定义表头顺序（按需要的顺序排列）
        List<List<String>> customHead = new ArrayList<>();
        customHead.add(Arrays.asList("id"));
        customHead.add(Arrays.asList("period"));
        customHead.add(Arrays.asList("shop_name"));
        customHead.add(Arrays.asList("brand_name"));
        customHead.add(Arrays.asList("country_name"));
        customHead.add(Arrays.asList("file_name"));
        customHead.add(Arrays.asList("settlement_id"));
        customHead.add(Arrays.asList("settlement_start_date"));
        customHead.add(Arrays.asList("settlement_end_date"));
        customHead.add(Arrays.asList("deposit_date"));
        customHead.add(Arrays.asList("total_amount"));
        customHead.add(Arrays.asList("currency"));
        customHead.add(Arrays.asList("transaction_type"));
        customHead.add(Arrays.asList("order_id"));
        customHead.add(Arrays.asList("merchant_order_id"));
        customHead.add(Arrays.asList("adjustment_id"));
        customHead.add(Arrays.asList("shipment_id"));
        customHead.add(Arrays.asList("marketplace_name"));
        customHead.add(Arrays.asList("amount_type"));
        customHead.add(Arrays.asList("amount_description"));
        customHead.add(Arrays.asList("amount"));
        customHead.add(Arrays.asList("fulfillment_id"));
        customHead.add(Arrays.asList("posted_date"));
        customHead.add(Arrays.asList("posted_date_time"));
        customHead.add(Arrays.asList("order_item_code"));
        customHead.add(Arrays.asList("merchant_order_item_id"));
        customHead.add(Arrays.asList("merchant_adjustment_item_id"));
        customHead.add(Arrays.asList("sku"));
        customHead.add(Arrays.asList("quantity_purchased"));
        customHead.add(Arrays.asList("promotion_id"));
        customHead.add(Arrays.asList("fee_name"));
        customHead.add(Arrays.asList("listing_name"));

        // 3. 导出Excel
        EasyExcel.write(response.getOutputStream(), Buy.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .sheet("待处理SKU")
                .head(customHead)  // 设置自定义表头
                .doWrite(convertDataToCustomOrder(list)); // 转换数据顺序
    }

    /**
     * 将原始数据转换为与自定义表头匹配的顺序
     */
    private List<List<Object>> convertDataToCustomOrder(List<Vt> dataList) {
        List<List<Object>> result = new ArrayList<>();
        for (Vt vt : dataList) {
            List<Object> row = new ArrayList<>();
            row.add(vt.getId());
            row.add(vt.getPeriod());
            row.add(vt.getShop_name());
            row.add(vt.getBrand_name());
            row.add(vt.getCountry_name());
            row.add(vt.getFile_name());
            row.add(vt.getSettlement_id());
            row.add(vt.getSettlement_start_date());
            row.add(vt.getSettlement_end_date());
            row.add(vt.getDeposit_date());
            row.add(vt.getTotal_amount());
            row.add(vt.getCurrency());
            row.add(vt.getTransaction_type());
            row.add(vt.getOrder_id());
            row.add(vt.getMerchant_order_id());
            row.add(vt.getAdjustment_id());
            row.add(vt.getShipment_id());
            row.add(vt.getMarketplace_name());
            row.add(vt.getAmount_type());
            row.add(vt.getAmount_description());
            row.add(vt.getAmount());
            row.add(vt.getFulfillment_id());
            row.add(vt.getPosted_date());
            row.add(vt.getPosted_date_time());
            row.add(vt.getOrder_item_code());
            row.add(vt.getMerchant_order_item_id());
            row.add(vt.getMerchant_adjustment_item_id());
            row.add(vt.getSku());
            row.add(vt.getQuantity_purchased());
            row.add(vt.getPromotion_id());
            row.add(vt.getFee_type());
            row.add(vt.getListing_name());
            result.add(row);
        }
        return result;
    }

    /**
     * 将原始数据转换为与自定义表头匹配的顺序
     */
    private List<List<Object>> convertDataToNonAmazonOrder(List<Vt> dataList) {
        List<List<Object>> result = new ArrayList<>();
        for (Vt vt : dataList) {
            List<Object> row = new ArrayList<>();
            row.add(vt.getOrder_id());

            result.add(row);
        }
        return result;
    }
}
